﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TS2015.Models;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Text;
using System.Data.OleDb;

namespace TS2015.Areas.Admin.Controllers
{
    public class CandidateManagementController : Controller
    {
        TS2015Context db = new TS2015Context();
        // GET: Admin/CandidateManagement
        public ActionResult CandidateList()
        {
            Database.SetInitializer<TS2015Context>(null);
            ViewBag.ChuyenNganh = db.TbChuyenNganhs.ToList();
            ViewBag.Truong = db.TbTruongs.ToList();
            ViewBag.Nganh = db.TbNganhs.ToList();
            //ViewBag.Truong = new SelectList(db.TbTruongs.ToList(), "MaTruong", "TenTruong");
            ViewBag.KhuVuc = db.TbKhuVucs.ToList();
            ViewBag.XepLoaiHS = db.TbXepLoaiHS.ToList();
            ViewBag.DanToc = db.TbDanTocs.ToList();
            ViewBag.DoiTuongUuTien = db.TbDoiTuongUuTiens.ToList();
            ViewBag.KhoiThi = db.TbKhoiThis.ToList();
            ViewBag.HeDaoTao = db.TbHeDaoTaos.ToList();

            if(!Request.IsAjaxRequest())
                return View();
            
            return PartialView();
        }
        public ActionResult EditingPopup_ReadCandidateList([DataSourceRequest] DataSourceRequest request)
        {
            return Json(db.TbThiSinhs.ToDataSourceResult(request));
        }
        public ActionResult EditingPopup_CreateCandidateList([DataSourceRequest] DataSourceRequest request, TbThiSinh data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.TbThiSinhs.Add(data);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult EditingPopup_UpdateCandidateList([DataSourceRequest] DataSourceRequest request, TbThiSinh data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.Entry(data).State = EntityState.Modified;
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult EditingPopup_DestroyCandidateList([DataSourceRequest] DataSourceRequest request, TbThiSinh data)
        {
            if (data != null)
            {
                TbThiSinh itemdata = db.TbThiSinhs.First(item => item.MaTS == data.MaTS);
                db.TbThiSinhs.Remove(itemdata);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }

        public int manganh;
        
        public ActionResult PhieuDangKy(string id)
        {
            TbThiSinh ThiSinh = new TbThiSinh();
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    //Database.SetInitializer<TS2015Context>(null);
                    ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "MaNganh", "TenNganh");
                    ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
                    ViewBag.Truong = new SelectList(db.TbTruongs.ToList(), "MaTruong", "TenTruong");
                    ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
                    ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
                    ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
                    ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
                    ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                }
                else
                {
                    
                    ThiSinh = db.TbThiSinhs.Include(e=>e.TbChuyenNganh).First(e => e.MaTS == id);
                    //int ma = ThiSinh.MaChuyenNganh;
                   var  manganh = (from m in db.TbChuyenNganhs where (m.MaChuyenNganh == ThiSinh.MaChuyenNganh) select m).First().MaNganh;
                   //ThiSinh.NgaySinh.ToString("{0:dd/MM/yyyy}"); 
                   ThiSinh.GioiTinh.ToString();
                    ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "MaNganh", "TenNganh", manganh);
                    ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh", ThiSinh.MaChuyenNganh);
                    ViewBag.Truong = new SelectList(db.TbTruongs.ToList(), "MaTruong", "TenTruong", ThiSinh.MaTruong);
                    ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc", ThiSinh.MaKhuVuc);
                    ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS", ThiSinh.MaXepLoaiHS);
                    ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc", ThiSinh.MaDanToc);
                    ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong", ThiSinh.MaDoiTuong);
                    ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi", ThiSinh.MaKhoiThi);
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao", ThiSinh.MaHeDaoTao);
                    ThiSinh.LanSuaCuoi = DateTime.Now;
                }
            }
            

            if (Request.IsAjaxRequest())
                return PartialView(ThiSinh);

            return View(ThiSinh);
        }

        public ActionResult CreateCandidate(string id)
        {
            TbThiSinh item = new TbThiSinh();
            SelectList ChuyenNganh = null;
            SelectList Truong = null;
            SelectList KhuVuc = null;
            SelectList XepLoaiHS = null;
            SelectList DanToc = null;
            SelectList DoiTuongUuTien = null;
            SelectList KhoiThi = null;
            SelectList HeDaoTao = null;
            if(ModelState.IsValid)
            {
                if(id != null)
                {
                    item = db.TbThiSinhs.First(e => e.MaTS == id);
                    Truong = new SelectList(db.TbTruongs.ToList(), "MaTruong", "TenTruong", item.MaTruong);
                    KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc", item.MaKhuVuc);
                    XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS", item.MaXepLoaiHS);
                    DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc", item.MaDanToc);
                    DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong", item.MaDoiTuong);
                    KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi", item.MaKhoiThi);
                    HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao", item.MaHeDaoTao);
                    ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh", item.MaChuyenNganh);
                }
                else
                {
                    ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
                    Truong = new SelectList(db.TbTruongs.ToList(), "MaTruong", "TenTruong");
                    KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
                    XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
                    DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
                    DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
                    KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
                    HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                }
            }
                ViewBag.Truong = Truong;
                ViewBag.KhuVuc = KhuVuc;
                ViewBag.XepLoaiHS = XepLoaiHS;
                ViewBag.DanToc = DanToc;
                ViewBag.DoiTuongUuTien = DoiTuongUuTien;
                ViewBag.KhoiThi = KhoiThi;
                ViewBag.HeDaoTao = HeDaoTao;
                ViewBag.ChuyenNganh = ChuyenNganh;

            if (!Request.IsAjaxRequest())
                return View(item);

            return PartialView(item);
        }
        [HttpPost]
        public ActionResult CreateCandidate(TbThiSinh item)
        {
            if(item != null)
            {
                
                item.NgayDangKi = DateTime.Now;
                //item.NgaySinh = DateTime.Now;
                if(item.MaTS != null)
                {
                    db.Entry(item).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    item.MaTS = GetID();
                    //item.NgayDongTien = DateTime.Now;
                    //item.NgayHoanThanhDK = DateTime.Now;
                    item.MaHeDaoTao = 1;
                    db.TbThiSinhs.Add(item);
                    SaveChanges(db);
                }
                
            }
            ViewBag.Truong = new SelectList(db.TbTruongs.ToList(), "MaTruong", "TenTruong", item.MaTruong);
            ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc", item.MaKhuVuc);
            ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS", item.MaXepLoaiHS);
            ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc", item.MaDanToc);
            ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong", item.MaDoiTuong);
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi", item.MaKhoiThi);
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao",item.MaHeDaoTao);
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh", item.MaChuyenNganh);
            TempData["Message"] = "Lưu thành công!";
            return RedirectToAction("CandidateList","CandidateManagement");
        }
        private void SaveChanges(DbContext context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new DbEntityValidationException(
                    "Entity Validation Failed - errors follow:\n" +
                    sb.ToString(), ex
                ); // Add the original exception as the innerException
            }
        }
        #region Import Excel
        //[HttpPost]
        //public ActionResult ImportExcel()
        //{
        //    if(Request.Files["ImportExcel"].ContentLength > 0)
        //    {
        //        string Extension = System.IO.Path.GetExtension(Request.Files["ImportExcel"].FileName);
        //        string[] str = Extension.Split('.');
        //        string Name = str[0];
        //        string Type = str[1];
        //        if(Type == "xls" || Type == "xlsx")
        //        {
        //            string path = string.Concat(Server.MapPath("~/Uploads/File" + DateTime.Now.ToString("yyyymmddhhmmssfff") + Name + "." + Type));
        //            Request.Files["ImportExcel"].SaveAs(path);
        //            OleDbConnection oledbcon = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=" + path + ";extended properties=excel 12.0;");
        //            oledbcon.Open();
        //            OleDbCommand oledbcmd = new OleDbCommand("Select * from [Sheet1$]", oledbcon);
        //            OleDbDataAdapter oledbda = new OleDbDataAdapter();
        //            oledbcmd.Connection = oledbcon;
        //            ddlSelectSheet.Items.Clear();
        //            ddlSelectSheet.DataSource = oledbcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        //            ddlSelectSheet.DataTextField = "TABLE_NAME";
        //            ddlSelectSheet.DataValueField = "TABLE_NAME";
        //            ddlSelectSheet.DataBind();
        //            oledbcon.Close();
        //        }
                
        //    }
        //    return RedirectToAction("Import");
        //}
        #endregion
        public string GetID()
        {
            string ID = "";
            var MaTS = (from p in db.TbThiSinhs orderby (p.MaTS) descending select p).Take(1).First();
            int Cuoi;
            string LastID;
            int NextID;
            
            if(MaTS==null)
            {
                NextID = 1;
            }
            else
            {
                Cuoi = Convert.ToInt32(MaTS.MaTS.ToString().Substring(4)) + 1;
                LastID = Cuoi.ToString();
                if(LastID == null)
                {
                    LastID = DateTime.Now.ToString("yyyy") + "00001";
                }
                NextID = Cuoi;  
            }
            ID = DateTime.Now.ToString("yyyy") + NextID.ToString("00000");
            return ID;
        }
    }
}